package com.smart.manager.weixin.mp.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.common.entities.option.SelectOption;
import com.smart.common.exception.SmartException;
import com.smart.manager.weixin.mp.entities.bodys.RWeixinMpTags;
import com.smart.manager.weixin.mp.entities.models.WeixinMpTags;
import com.smart.manager.weixin.mp.entities.models.query.QWeixinMpTags;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserTagService;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公众号接入配置 数据仓库
 *
 * @author Administrator
 * @date 2023/04/02
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class WxmpTagsRepository {

    private final WxMpService wxMpService;

    public Page<WeixinMpTags> pageList(RWeixinMpTags.SearchBody search) {


        QWeixinMpTags query = new QWeixinMpTags();
        Opt.ofBlankAble(search.getName()).ifPresent(x -> query.tagName.contains(x));
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<WeixinMpTags>().load(query.findPagedList());
    }

    public void add(RWeixinMpTags.EditBody body) {

        try {
            WeixinMpTags weixinMpAccount = new QWeixinMpTags().appId.eq(body.getAppId())
                    .tagName.eq(body.getTagName()).setMaxRows(1).findOne();
            Assert.isNull(weixinMpAccount, "标签信息已存在");
            WeixinMpTags rs = BeanUtil.copyProperties(body, WeixinMpTags.class);
            WxMpUserTagService userTagService = wxMpService.switchoverTo(body.getAppId()).getUserTagService();
            WxUserTag wxUserTag = userTagService.tagCreate(body.getTagName());

            rs.setTagId(wxUserTag.getId()).setTagName(wxUserTag.getName());
            //将数据同步到微信
            rs.save();
        } catch (WxErrorException e) {
            throw new SmartException("标签创建失败:" + e.getMessage());
        }
    }


    public void update(Long id, RWeixinMpTags.EditBody body) {
        try {
            WeixinMpTags record = new QWeixinMpTags().id.eq(id).setMaxRows(1).findOne();
            Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
            BeanUtil.copyProperties(body, record);
            WxMpUserTagService userTagService = wxMpService.switchoverTo(body.getAppId()).getUserTagService();
            userTagService.tagUpdate(record.getTagId(), record.getTagName());
            Objects.requireNonNull(record).update();
        } catch (WxErrorException e) {
            throw new SmartException("标签修改失败:" + e.getMessage());
        }
    }

    public void delByIds(List<Long> ids) {


        List<WeixinMpTags> list = new QWeixinMpTags().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);


        list.forEach(x -> {
            if (!x.getTagName().equals("星标组")) {
                WxMpUserTagService userTagService = wxMpService.switchoverTo(x.getAppId()).getUserTagService();
                try {
                    userTagService.tagDelete(x.getTagId());
                    x.delete();
                } catch (WxErrorException e) {
                    throw new SmartException("删除标签失败:" + e.getMessage());
                }
            }
        });


    }


    /**
     * @return {@code List<SelectOption>}
     */
    public List<SelectOption> getOptions() {
        QWeixinMpTags query = new QWeixinMpTags();
        return query.findStream()
                .map(x -> new SelectOption().setLabel(x.getTagName())
                        .setValue(x.getId().toString()).setDisabled(false))
                .collect(Collectors.toList());
    }


    public void syncTags(String appId) {
        try {

            WxMpUserTagService userTagService = wxMpService.switchoverTo(appId).getUserTagService();
            List<WxUserTag> wxUserTags = userTagService.tagGet();
            List<WeixinMpTags> list = new QWeixinMpTags().appId.eq(appId).findList();
            if (CollectionUtil.isEmpty(wxUserTags)) {
                return;
            }
            ArrayList<WeixinMpTags> addList = new ArrayList<>();
            if (CollectionUtil.isEmpty(list)) {
                List<WeixinMpTags> insArr = wxUserTags.stream().map(x ->
                                new WeixinMpTags().setTagId(x.getId()).setTagName(x.getName()).setTagCount(0))
                        .collect(Collectors.toList());
                addList.addAll(insArr);
            } else {
                List<Long> tagIds = list.stream().map(WeixinMpTags::getTagId).collect(Collectors.toList());
                wxUserTags.forEach(item -> {
                    if (!tagIds.contains(item.getId())) {
                        WeixinMpTags mx = new WeixinMpTags().setTagId(item.getId()).setTagName(item.getName()).setTagCount(0);
                        addList.add(mx);
                    }
                });
            }
            Opt.ofEmptyAble(addList).ifPresent(DB::saveAll);
        } catch (WxErrorException exception) {
            throw new SmartException("微信标签数据同步失败:" + exception.getMessage());
        }
    }
}
